package com.wonders.healthcitydoctor.ui.webview;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.EaseConstant;
import com.wonders.healthcitydoctor.AppApplication;
import com.wonders.healthcitydoctor.HtmlUrl;
import com.wonders.healthcitydoctor.MainActivity;
import com.wonders.healthcitydoctor.R;
import com.wonders.healthcitydoctor.eventbus.StartBrotherEvent;
import com.wonders.healthcitydoctor.hx.ChatActivity;
import com.wonders.healthcitydoctor.hx.ConversationListActivity;
import com.wonders.healthcitydoctor.ui.base.BaseMainFragment;
import com.wonders.healthcitydoctor.ui.map.QrCodeFragment;
import com.wonders.healthcitydoctor.util.DateUtil;
import com.wonders.healthcitydoctor.util.LogUtil;
import com.wonders.healthcitydoctor.util.SPUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class MainWebviewFragment extends BaseMainFragment implements View.OnClickListener{
    private static final String URL = "URL";
    private static final String TITEL = "TITEL";
    private static final String TYPE = "TYPE";
    @BindView(R.id.webView)
    BridgeWebView webView;
    @BindView(R.id.progressbar)
    ProgressBar progressbar;

    private String url="";
    private String title="";
    private String type="";
    private int layoutId=0;
    String username = "";
    String password = "";
    String isSavaPass = "";
    String isAutoLogin = "";
    private final int RC_EMCLIENT_LOGOUT=0x134;
    private final int RC_HX_PERM=0x135;

    public MainWebviewFragment() {
        // Required empty public constructor
    }

    public static MainWebviewFragment newInstance(String url, String titile, String type) {
        MainWebviewFragment fragment = new MainWebviewFragment();
        Bundle args = new Bundle();
        args.putString(URL, url);
        args.putString(TITEL, titile);
        args.putString(TYPE, type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            url = getArguments().getString(URL);
            title = getArguments().getString(TITEL);
            type = getArguments().getString(TYPE);
        }
        setLayout();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(layoutId, container, false);
        ButterKnife.bind(this, view);
        initTile(view);
//        showProgressDialog();
        LogUtil.i("data===", title + "," + url+","+type);

        initWebView();

        webView.loadUrl(url);
        LogUtil.i("onCreateView===", "webviewFrageOnCreateView");
        return view;
    }

    private void initWebView() {
        WebSettings webSettings = webView.getSettings();
        String ua = webSettings.getUserAgentString();
        webSettings.setUserAgentString(ua + " android_appName");
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDefaultTextEncodingName("UTF-8");
        webSettings.setDomStorageEnabled(true);// 开启 DOM storage API 功能
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);  //设置 缓存模式
        //开启 database storage API 功能
        webSettings.setDatabaseEnabled(false);
        //开启 Application Caches 功能
        webSettings.setAppCacheEnabled(false);
        String cookie=(String) SPUtils.get(getContext().getApplicationContext(),getString(R.string.cookie),"");
        syncCookie(getContext().getApplicationContext(), cookie);

//        registerJsbridge();
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                progressbar.setProgress(newProgress);
                if (newProgress == 100) {
//                    hideProgressDialog();
                    progressbar.setVisibility(View.GONE);
//                    registerJsbridge();
                }
            }
        });
        webView.setWebViewClient(new BridgeWebViewClient(webView) {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });
        registerJsbridge();
    }

    public void initTile(View view) {
    }

    public void gotoWebView(String url, String title, String type) {

    }

    public void getCurrentJwd(String data, CallBackFunction function) {

    }

    // 设置cookie
    public void syncCookie(Context context, String cookies) {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeSessionCookie();//移除
//        cookieManager.removeAllCookie();
        LogUtil.i("cookie",url+","+cookies);
        cookieManager.setCookie( url, cookies);
        CookieSyncManager.getInstance().sync();
    }

    public void registerJsbridge() {
        webView.registerHandler("gotoWebView", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
//                LogUtil.i("gotoWebView", " " + data);
//                function.onCallBack("submitFromWeb exe, response data 中文 from Java");
                LogUtil.i("gotoWebView", " " + data);
                JSONObject jsonData;
                try {
                    jsonData = new JSONObject(data);
                    url = jsonData.getString("url");
                    if (jsonData.has("title")) {
                        title = jsonData.getString("title");
                    }else {
                        title="";
                    }
                    if (jsonData.has("type")){
                        type= jsonData.getString("type");
                    }else {
                        type="";
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                gotoWebView(HtmlUrl.hostIp + url, title,type);
            }

        });
        webView.registerHandler("gotoHome", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                LogUtil.i("gotoHome", " " + data);
                saveLoginInfo(data);
//                Intent intent = new Intent(getContext().getApplicationContext(), MainActivity.class);
//                startActivity(intent);
                CookieManager cookieManager = CookieManager.getInstance();
                cookieManager.setAcceptCookie(true);
//                    cookieManager.removeAllCookie();
                //获取登录后的cookie
                String CookieStr = cookieManager.getCookie(HtmlUrl.loginUrl);
                LogUtil.i("cookie", CookieStr + "");
                SPUtils.put(getContext().getApplicationContext(), getString(R.string.cookie), CookieStr);
                //环信
                String easeUserName = (String) SPUtils.get(getContext().getApplicationContext(), getString(R.string.easeUserName), "");
                String easePassword = (String) SPUtils.get(getContext().getApplicationContext(), getString(R.string.easePassword), "");
//                final String easePhoto = (String) SPUtils.get(AppApplication.getContextObject(), getString(R.string.easePhoto), "");
//                final String easeNickname = (String) SPUtils.get(AppApplication.getContextObject(), getString(R.string.easeNickname), "");

                LogUtil.i("hx",easeUserName+","+easePassword);
                EMClient.getInstance().login(easeUserName, easePassword, new EMCallBack() {//回调
                    @Override
                    public void onSuccess() {
                        EMClient.getInstance().chatManager().loadAllConversations();
                        Log.i(TAG, "登录聊天服务器成功！");
//                        if (easeNickname!=null&&!"".equals(easeNickname)) {
//                            HxSPUtils.put(AppApplication.getContextObject(), Constant.EASENICKNAME, easeNickname);
//                        }
//                        if (easePhoto!=null&&!"".equals(easePhoto)) {
//                            HxSPUtils.put(AppApplication.getContextObject(), Constant.EASEPHOTO, easePhoto);
//                        }
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Intent intent = new Intent(getContext().getApplicationContext(), MainActivity.class);
                                startActivity(intent);
                                getActivity().finish();
                            }
                        });
                    }
//
                    @Override
                    public void onProgress(int progress, String status) {
                    }

                    @Override
                    public void onError(int code, final String message) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getContext(), "登录聊天服务器失败！"+message,Toast.LENGTH_SHORT).show();
                                emclientLogout();
                                LogUtil.i("登录聊天服务器失败：" + message);
                            }
                        });
                    }
                });
                //==========


            }

        });
        webView.registerHandler("easemod", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                LogUtil.i("easemod", " " + data);
                JSONObject jsonData;
                try {
                    jsonData = new JSONObject(data);
                    String userName = jsonData.getString("userName");
                    Intent chat = new Intent(getContext().getApplicationContext(), ChatActivity.class);
                    chat.putExtra(EaseConstant.EXTRA_USER_ID,userName);  //对方账号
                    startActivity(chat);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                EventBus.getDefault().post(new StartBrotherEvent(QrCodeFragment.newInstance(HtmlUrl.hostIp + url)));

            }

        });
        webView.registerHandler("getConversationList", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                LogUtil.i("getConversationList", " " + data);
                conversationList();

            }

        });
        webView.registerHandler("createCode", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                LogUtil.i("createCode", " " + data);
                JSONObject jsonData;
                try {
                    jsonData = new JSONObject(data);
                    url = jsonData.getString("url");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                EventBus.getDefault().post(new StartBrotherEvent(QrCodeFragment.newInstance(HtmlUrl.hostIp + url)));

            }

        });
    }
    @AfterPermissionGranted(RC_HX_PERM)
    public void conversationList() {
        if (Build.VERSION.SDK_INT >= 23) {
            String[] PERMISSIONS = {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};
            if (EasyPermissions.hasPermissions(getContext().getApplicationContext(), PERMISSIONS)) {
                // Have permission, do the thing!
                startActivity(new Intent(getContext().getApplicationContext(),ConversationListActivity.class));

            } else {
                // Ask for one permission
                EasyPermissions.requestPermissions(this, "需要读写存储的权限",
                        RC_HX_PERM, PERMISSIONS);
            }
        } else {
            startActivity(new Intent(getContext().getApplicationContext(),ConversationListActivity.class));
        }
    }
    @AfterPermissionGranted(RC_EMCLIENT_LOGOUT)
    public void emclientLogout() {
        if (Build.VERSION.SDK_INT >= 23) {
            String[] PERMISSIONS = {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};
            if (EasyPermissions.hasPermissions(getContext().getApplicationContext(), PERMISSIONS)) {
                // Have permission, do the thing!
                EMClient.getInstance().logout(false);

            } else {
                // Ask for one permission
                EasyPermissions.requestPermissions(this, "需要读取存储的权限",
                        RC_EMCLIENT_LOGOUT, PERMISSIONS);
            }
        } else {
            EMClient.getInstance().logout(false);
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        super.onPermissionsDenied(requestCode, perms);
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        super.onPermissionsGranted(requestCode, perms);
        switch (requestCode){
            case RC_HX_PERM:
            startActivity(new Intent(getContext().getApplicationContext(),ConversationListActivity.class));
            break;
            case RC_EMCLIENT_LOGOUT:
                EMClient.getInstance().logout(false);
                break;
        }

    }
    private void saveLoginInfo(String data) {
        JSONObject jsonData;
        try {
            jsonData = new JSONObject(data);
            username = jsonData.getString("username");
            password = jsonData.getString("password");
            isSavaPass = jsonData.getString("isSavaPass");
            isAutoLogin = jsonData.getString("isAutoLogin");
            String easemobStr = jsonData.getString("easemob");
            JSONObject easemobJsonObject = new JSONObject(easemobStr);
            String easeUserName = easemobJsonObject.getString("username");
            String easePassword = easemobJsonObject.getString("password");
//            String easePhoto = easemobJsonObject.getString("photo");
//            String easeNickname = easemobJsonObject.getString("nickname");

            SPUtils.put(getContext().getApplicationContext(), getString(R.string.username), username);
            SPUtils.put(getContext().getApplicationContext(),"password", password);
            SPUtils.put(getContext().getApplicationContext(), getString(R.string.isSavaPass), isSavaPass);
            SPUtils.put(getContext().getApplicationContext(), getString(R.string.isAutoLogin), isAutoLogin);

            SPUtils.put(getContext().getApplicationContext(), getString(R.string.easeUserName), easeUserName);
            SPUtils.put(getContext().getApplicationContext(), getString(R.string.easePassword), easePassword);
//            SPUtils.put(getContext().getApplicationContext(), getString(R.string.easePhoto), easePhoto);
//            SPUtils.put(getContext().getApplicationContext(), getString(R.string.easeNickname), easeNickname);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private void setLayout(){
        if (title==null){
            title="";
        }
       switch (title){
           case "工作报告":
               layoutId=R.layout.fragment_home;
               break;
           case "预约":
               layoutId=R.layout.fragment_treatment;
               break;
           case "签约居民":
               layoutId=R.layout.fragment_health;
               break;
           case "个人中心":
               layoutId=R.layout.fragment_person;
               break;
           default:
               layoutId=R.layout.fragment_login;

       }

    }

    public void setTitle(View view, String title, int leftSrc, int rightSrc){
        ImageView img_left=(ImageView)view.findViewById(R.id.image_left);
        ImageView img_right=(ImageView)view.findViewById(R.id.image_right);
        TextView txt_title=(TextView)view.findViewById(R.id.tv_title);
        txt_title.setText(title);
        if (leftSrc!=0) {
            img_left.setImageResource(leftSrc);
        }
        if (rightSrc!=0) {
            img_right.setImageResource(rightSrc);
        }
        img_left.setOnClickListener(this);
        img_right.setOnClickListener(this);
    }
    public void setTitle(View view, String title, String rightText, int imgSrc){
        ImageView img_back=(ImageView)view.findViewById(R.id.image_back);
        TextView txt_title=(TextView)view.findViewById(R.id.tv_title);
        TextView right_text=(TextView)view.findViewById(R.id.right_text);
        ImageView right_img=(ImageView)view.findViewById(R.id.right_img);
        txt_title.setText(title);
        if (!rightText.equals("")){
            right_text.setText(rightText);
            right_text.setOnClickListener(this);
        }
        if (imgSrc!=0){
            right_img.setImageResource(imgSrc);
            right_img.setOnClickListener(this);
        }
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                    _mActivity.onBackPressed();
                pop();
                InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
        });

    }
    public void setEditTitle(View view, String hint, int leftSrc, int rightSrc){
        ImageView img_left=(ImageView)view.findViewById(R.id.image_left);
        ImageView img_right=(ImageView)view.findViewById(R.id.image_right);
        TextView text_hint=(TextView) view.findViewById(R.id.text_hint);
        final EditText et_title=(EditText) view.findViewById(R.id.et_title);
        final LinearLayout mLayoutDefaultText = (LinearLayout) view.findViewById(R.id.layout_default);
        text_hint.setText(hint);
        if (leftSrc!=0) {
            img_left.setImageResource(leftSrc);
        }
        if (rightSrc!=0) {
            img_right.setImageResource(rightSrc);
        }
        img_left.setOnClickListener(this);
        img_right.setOnClickListener(this);
        et_title.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId== EditorInfo.IME_ACTION_DONE){
                    setOnEditClickListener(v,et_title.getText().toString());
                }
                return false;
            }
        });

        // editText 离开监听
        et_title.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                // hasFocus 为false时表示点击了别的控件，离开当前editText控件
                if (!hasFocus) {
                    if ("".equals(et_title.getText().toString())) {
                        mLayoutDefaultText.setVisibility(View.VISIBLE);
                    }
                }
                else {
                    mLayoutDefaultText.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.image_left:
                setOnLeftClickListener(v);
                break;
            case R.id.image_right:
                setOnRightClickListener(v);
                break;
        }
    }
    public void setOnLeftClickListener(View v){


    }
    public void setOnRightClickListener(View v){
    }
    public void setOnEditClickListener(View v, String editText){
    }
    protected void initLoginInfo() {
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeSessionCookie();
//        cookieManager.removeAllCookie();
        boolean b = isRemoveCookie();
        LogUtil.i("isRemoveCookie", b + "");
        username = (String) SPUtils.get(getContext().getApplicationContext(), getString(R.string.username), "");
        password = (String) SPUtils.get(getContext().getApplicationContext(), "password", "");
        isAutoLogin = (String) SPUtils.get(getContext().getApplicationContext(), getString(R.string.isAutoLogin), "");
        isSavaPass = (String) SPUtils.get(getContext().getApplicationContext(), getString(R.string.isSavaPass), "");
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put(getString(R.string.username), username);
            jsonObject.put("password", password);
            jsonObject.put(getString(R.string.isAutoLogin), isAutoLogin);
            jsonObject.put(getString(R.string.isSavaPass), isSavaPass);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        LogUtil.i("initLoginInfo", jsonObject.toString());

        webView.callHandler("initLoginInfo", jsonObject.toString(), new CallBackFunction() {
            @Override
            public void onCallBack(String data) {

            }
        });
//        CookieManager cookieManager = CookieManager.getInstance();
//        cookieManager.setAcceptCookie(true);
////                    cookieManager.removeAllCookie();
//        //获取登录后的cookie
//        String CookieStr = cookieManager.getCookie(HtmlUrl.loginUrl);
//        LogUtil.i("cookie", CookieStr + "");
//        SPUtils.put(getApplicationContext(), getString(R.string.cookie), CookieStr);
//        finish();

    }
    public boolean isRemoveCookie(){
        boolean isRemoveCookie=false;
        String currentTime= DateUtil.ConverToString(new Date());
        String preTime=(String) SPUtils.get(getContext().getApplicationContext(),getString(R.string.touchTime),"0000-00-00 00:00:00");
        long chaTime=DateUtil.timeCha(preTime,new Date());
        LogUtil.i("timecha",chaTime+","+preTime+","+currentTime);
        if (chaTime>=30){
            CookieSyncManager.createInstance(getContext().getApplicationContext());
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeSessionCookie();//移除
//            cookieManager.removeAllCookie();
//            SPUtils.put(getContext().getApplicationContext(),getString(R.string.cookie),"");
//            SPUtils.put(getContext().getApplicationContext(),getString(R.string.username),"");
//            SPUtils.put(getContext().getApplicationContext(),getString(R.string.password),"");
//            SPUtils.put(getContext().getApplicationContext(),getString(R.string.isSavaPass),"");
            SPUtils.put(getContext().getApplicationContext(),getString(R.string.isAutoLogin),"");
            isRemoveCookie=true;
        }
        SPUtils.put(getContext().getApplicationContext(),getString(R.string.touchTime),currentTime);
        return isRemoveCookie;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (webView != null) {
            // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再
            // destory()
            ViewParent parent = webView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(webView);
            }

            webView.stopLoading();
            // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
            webView.getSettings().setJavaScriptEnabled(false);
            webView.clearHistory();
            webView.clearView();
            webView.removeAllViews();

            try {
                webView.destroy();
            } catch (Throwable ex) {
                ex.printStackTrace();
            }
//            InputCleanLeakUtils.fixInputMethodManagerLeak(getContext());
        }
    }

}